package kassiopeia.plugin.crawler.filter;

import java.util.Arrays;
import java.util.List;

import kassiopeia.plugin.Event;
import kassiopeia.plugin.ProcessorPlugin;

import org.apache.log4j.Logger;

import com.google.common.base.Splitter;
import com.google.common.collect.Lists;

public class ContentFilterPlugin extends ProcessorPlugin {

    private static final Logger logger = Logger.getLogger(ContentFilterPlugin.class);

    public static final String MIME_TYPE_HEADER_NAME = "MIME_TYPE";
    private static final String OUTPUT = "out";
    public static final String ALLOWED_MIME_TYPES_PARAM = "allowed-mime-types";

    private List<String> allowedMimeTypes;

    @Override
    public void beforeTask() {
        logger.info("ContentFilterPlugin plugin constructed : " + getContext().getPluginInstanceId());

        String allowedMimeParam = getContext().getParameter(ALLOWED_MIME_TYPES_PARAM);
        Iterable<String> elements = Splitter.on(" ").omitEmptyStrings().trimResults().split(allowedMimeParam);
        allowedMimeTypes = Lists.newArrayList(elements);

        logger.debug("Allowed MIME content: " + Arrays.toString(allowedMimeTypes.toArray(new String[0])));
    }

    @Override
    public final void process(Event event) {
        String contentMimeType = event.getHeader(MIME_TYPE_HEADER_NAME, String.class);

        if(contentMimeType != null && isMimeAllowed(contentMimeType)) {
            logger.debug("Accepting event of type: " + contentMimeType);
            getContext().sendLocally(event, OUTPUT);
        } else {
            logger.debug("Discarding event of type: " + contentMimeType);
        }
    }

    private boolean isMimeAllowed(String contentMimeType) {
        for(String allowedMimeType : allowedMimeTypes) {
            if(allowedMimeType.equals(contentMimeType)) {
                return true;
            }
        }
        return false;
    }
}
